package itsm.isperp.module.controller.api.wechat;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.domain.IBean;
import itsm.isperp.framework.security.encoding.DESHelper;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.dto.app.VUserAccount;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.entity.customer.CusCustomer;
import itsm.isperp.module.service.app.AppDepartmentService;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.app.UserAccountService;
import itsm.isperp.module.service.customer.CusCustomerService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("api/wechat/setting")
public class WXRegisterController {

  @Autowired
  CusCustomerService cusCustomerService;
  @Autowired
  AppUserService appUserService;

  @Autowired
  WxMpService wxMpService;

  @Autowired
  SimpMessagingTemplate simpMessagingTemplate;

  @RequestMapping("register")
  public ModelAndView register(String openid, String error) throws IOException {
    ModelAndView mv = new ModelAndView();
    mv.addObject("openid", openid);
    mv.addObject("error", error);
    AppUser r = appUserService.findByOpenid(openid, "id");
    // 用户已经注册则进入提醒页面
    if (r != null) {
      mv.setViewName("api/wechat/setting/registerNotice");
      mv.addObject("success", 1);
    } else {
      mv.setViewName("api/wechat/setting/register");
    }
    return mv;
  }

  @RequestMapping("register1")
  public ModelAndView register1(String openid) throws IOException {
    ModelAndView mv = new ModelAndView();
    mv.addObject("openid", openid);
    return mv;
  }

  /**
   * 注册新用户，第一步，输入客户名称
   * 
   * @param openid
   * @return
   */
  @RequestMapping("register2_1")
  public ModelAndView register2_1(String openid) {
    ModelAndView mv = new ModelAndView();
    mv.setViewName("api/wechat/setting/register2_1");
    mv.addObject("openid", openid);
    return mv;
  }

  /**
   * 注册新用户，第二步，选择客户，输入用户基本信息
   * 
   * @param openid
   * @param customerName
   * @return
   */
  @RequestMapping("register2_2")
  public ModelAndView register2_2(String openid, String customerName) {
    ModelAndView mv = new ModelAndView();
    mv.addObject("openid", openid);
    mv.addObject("customerName", customerName);

    JqGridRequest req = new JqGridRequest();
    req.setPageable(false);
    req.setSelectColumns("id", "name");
    req.addFilterRule("name", JqGridFilterRuleOp.cn, customerName);
    /*
     * DataResponse<CusCustomer> cusCustomers = cusCustomerService
     * .findAll(req);
     */
    mv.setViewName("api/wechat/setting/register2_2");
    mv.addObject("customers", "");

    return mv;
  }
  
  @RequestMapping("checkSave")
  @ResponseBody
  public ResultMessage checkSave(HttpServletRequest request,
      RedirectAttributes redirectAttributes)
  {
    String name = request.getParameter("name");
    String mobile = request.getParameter("mobile");
    AppUserService appUserService = ContextHolder
        .getSpringBean("appUserService");
    JqGridRequest req=new JqGridRequest();
    req.setSearchString(" mobile='"+mobile+"' and fullname<>'"+name+"' and (openid is not null)");
    AppUser u=appUserService.findOneByRequest(req);
    if(u!=null)
    {
      return ResultMessage.newInstance(false);
    }else
    {
      return ResultMessage.newInstance(true);
    }
    
  }

  /**
   * 
   * @param request
   * @param redirectAttributes
   * @return
   * @throws Exception
   */
  @RequestMapping("register2_3")
  public ModelAndView register2_3(HttpServletRequest request,
      RedirectAttributes redirectAttributes) throws Exception {
    ModelAndView mv = new ModelAndView();

    String openid = request.getParameter("openid");
    String cusDeptName = request.getParameter("cusDeptName");
    String cusDeptId = request.getParameter("cusDeptId");//这里实际是cus_customer_id
    String name = request.getParameter("name");
    String cusUserId=request.getParameter("cusUserId");
    String mobile = request.getParameter("mobile");
    String birthdayMonth = request.getParameter("birthdayMonth");
    String birthdayDay = request.getParameter("birthdayDay");
    String email = request.getParameter("email");
    String linkaddress = request.getParameter("linkaddress");
    String userDept=request.getParameter("userDept");
    JqGridRequest filter = new JqGridRequest();
    filter.setSelectColumns("id");
    filter.setRows(1);
    // filter.addFilterRule("customerId", JqGridFilterRuleOp.eq, cusCustomerId);
    filter.addFilterRule("id", JqGridFilterRuleOp.eq, cusUserId);
    List<AppUser> cusUserList = appUserService.findAll(filter);

    AppUser model = null;
    boolean newUser=false;
    // 如果存在此用户
    if (cusUserList.size() > 0) {
      AppUser oldmodel = cusUserList.get(0);
      model = oldmodel;
    } else {
      newUser=true;
      model = new AppUser();
      model.setId(HibernateUUIDGenerator.generate());
      model.setStatus("待审核");
      AppUser tuser = appUserService.findByUsername(mobile, "name","fullname");
      if (tuser == null)
        model.setName(mobile);
      else {
        String py = itsm.isperp.framework.utils.StringUtils.getPinYin(model
            .getFullname());
        UserAccountService userAccountService = ContextHolder
            .getSpringBean("userAccountService");
        VUserAccount account = userAccountService.findByUsername(py, "id");
        if (account != null) {
          py = py + 1;
        }
        model.setName(py);

      }
    }

    if (StringUtils.isNotEmpty(email)) {
      model.setEmail(email);
    }
    if (StringUtils.isNotEmpty(linkaddress)) {
      model.setAddress(linkaddress);
    }
    model.setOpenid(openid);
    try {
      WxMpUser u = wxMpService.userInfo(openid, null);
      model.setGender("1".equals(u.getSex()) ? "男" : "女");
      model.setNickname(u.getNickname());
      model.setHeadimgurl(u.getHeadImgUrl());
    } catch (Exception ex) {

    }
    //model.setCustomerId(cusCustomerId);
    model.setFullname(name);
    model.setMobile(mobile);
    model.setBirthdayDay(birthdayDay);
    model.setBirthdayMonth(birthdayMonth);
    //model.setCustomerName(cusName);
    model.setAreCustomer(true);
   // 
    if (cusUserList.size() > 0) 
    {
      Set<String> columns=new HashSet<String>();
      columns.add("openid");
      columns.add("mobile");
      columns.add("tel");
      columns.add("email");
      appUserService.dynamicUpdateSpecific(model, columns);
    }else
    {
      if(StringUtils.isNotEmpty(cusDeptId))
      {
        if(StringUtils.isEmpty(userDept))
        {
         // model.setAppDepartmentId(cusDeptId);
          AppDepartmentService appDepartmentService = ContextHolder
              .getSpringBean("appDepartmentService");
         String deptId=appDepartmentService.findDeptByCustomerId(cusDeptId);
         model.setAppDepartmentId(deptId);
         model.setCustomerId(cusDeptId);
         model.setCustomerName(cusDeptName);
        }else
        {
          model.setAppDepartmentId(userDept);
          model.setCustomerId(cusDeptId);
          model.setCustomerName(cusDeptName);
        }

      }
     // model.setEnable(false);
      model.setPassword("WP5Essdoi1Q=");
      appUserService.saveOrUpdate(model);
    }
    mv.addObject("id", model.getId());
    mv.addObject("openid", openid);
    mv.addObject("name", name);
    mv.addObject("newUser", newUser);
    mv.addObject("success", 1);
    mv.addObject("accountId", model.getName());
    mv.setViewName("api/wechat/setting/registerNotice");

    return mv;
  }
  
  /*
   * 新的注册方法
   */
  @RequestMapping("newRegister")
  public ModelAndView newRegister(HttpServletRequest request,
      RedirectAttributes redirectAttributes) throws Exception {
    ModelAndView mv = new ModelAndView();

    String openid = request.getParameter("openid");
    String cusDeptName = request.getParameter("cusDeptName");
    String cusDeptId = request.getParameter("cusDeptId");//这里实际是cus_customer_id
    String name = request.getParameter("name");
    String cusUserId=request.getParameter("cusUserId");
    String mobile = request.getParameter("mobile");
    String birthdayMonth = request.getParameter("birthdayMonth");
    String birthdayDay = request.getParameter("birthdayDay");
    String email = request.getParameter("email");
    String linkaddress = request.getParameter("linkaddress");
    String userDept=request.getParameter("userDept");
    
    JqGridRequest filter = new JqGridRequest();
    filter.addFilterRule("mobile", JqGridFilterRuleOp.eq, mobile);
    filter.addFilterRule("fullname", JqGridFilterRuleOp.eq, name);
    List<AppUser> cusUserList = appUserService.findAll(filter);

    AppUser model = null;
    boolean newUser=false;
    // 如果存在此用户
    if (cusUserList.size() > 0) {
      AppUser oldmodel = cusUserList.get(0);
      model = oldmodel;
    } else {
      newUser=true;
      model = new AppUser();
      model.setId(HibernateUUIDGenerator.generate());
      model.setName(mobile);
    }

    if (StringUtils.isNotEmpty(email)) {
      model.setEmail(email);
    }
    if (StringUtils.isNotEmpty(linkaddress)) {
      model.setAddress(linkaddress);
    }
    model.setOpenid(openid);
    try {
      WxMpUser u = wxMpService.userInfo(openid, null);
      model.setGender("1".equals(u.getSex()) ? "男" : "女");
      model.setNickname(u.getNickname());
      model.setHeadimgurl(u.getHeadImgUrl());
    } catch (Exception ex) {

    }
    model.setFullname(name);
    model.setMobile(mobile);
    model.setBirthdayDay(birthdayDay);
    model.setBirthdayMonth(birthdayMonth);
    model.setAreCustomer(true);
   // 
    if (cusUserList.size() > 0) 
    {
      Set<String> columns=new HashSet<String>();
      columns.add("openid");
      columns.add("mobile");
      columns.add("tel");
      columns.add("email");
      appUserService.dynamicUpdateSpecific(model, columns);
    }else
    {
      if(StringUtils.isNotEmpty(cusDeptId))
      {
        if(StringUtils.isEmpty(userDept))
        {
          AppDepartmentService appDepartmentService = ContextHolder
              .getSpringBean("appDepartmentService");
         String deptId=appDepartmentService.findDeptByCustomerId(cusDeptId);
         model.setAppDepartmentId(deptId);
         model.setCustomerId(cusDeptId);
         model.setCustomerName(cusDeptName);
        }else
        {
          model.setAppDepartmentId(userDept);
          model.setCustomerId(cusDeptId);
          model.setCustomerName(cusDeptName);
        }

      }
      model.setPassword("WP5Essdoi1Q=");
      model.setEnable(true);
      appUserService.saveOrUpdate(model);
    }
    mv.addObject("id", model.getId());
    mv.addObject("openid", openid);
    mv.addObject("name", name);
    mv.addObject("newUser", newUser);
    mv.addObject("success", 1);
    mv.addObject("accountId", model.getName());
    mv.setViewName("api/wechat/setting/registerNotice");

    return mv;
  }

  /**
   * 保存实体
   * 
   * @param model
   *          　一个继承与IBean接口的尸体　{@link IBean}
   * @return json结果数据
   * @throws IOException
   */
  @RequestMapping("save")
  public ModelAndView save(HttpServletRequest request,
      RedirectAttributes redirectAttributes) throws Exception {
    ModelAndView mv = new ModelAndView();
    mv.setViewName("api/wechat/setting/registerNotice");
    String openid = request.getParameter("openid");
    String registerType = request.getParameter("registerType");
    String accountId = request.getParameter("accountId");
    String password = request.getParameter("password");

    int result = 0;

    if ("1".equals(registerType)) {
      AppUser u = appUserService.findByUsername(accountId, password, "id");
      if (u != null) {
        result = 1;
        appUserService.updateOpenid(u.getId(), openid);
      } else {
        // 帐号绑定失败
        result = 2;
      }
    } else {

      String id = request.getParameter("id");

      UserAccountService userAccountService = ContextHolder
          .getSpringBean("userAccountService");
      VUserAccount u = userAccountService.findByUsername(accountId, "id");

      if (u == null) {
        result = 1;
        appUserService.updateUsername(id, accountId,
            DESHelper.encrypt(password));

        // ChatMessage cm = ChatUtils.receiveMessage(openid, name);
        // simpMessagingTemplate.convertAndSend("/chatMessage/result",
        // cm);
      } else {
        // 新帐号已经存在
        result = 2;
        mv.addObject("accountId", accountId);
        mv.setViewName("api/wechat/setting/register2_3");
      }

    }

    mv.addObject("success", result);
    mv.addObject("openid", openid);
    return mv;
  }

  @RequestMapping("autocompleteList")
  @ResponseBody
  public PageResponse<CusCustomer> autocompleteList(JqGridRequest request,
      HttpServletRequest req) {
    String term = req.getParameter("term");
    CusCustomerService cusCustomerService = ContextHolder
        .getSpringBean("cusCustomerService");

    if (StringUtils.isNotEmpty(term)) {
      request.isPageable(false);
      request.setSelectColumns("id", "name");
      request.setGroupBy("id,name");
      request.setSearchString(" ((name is not null) and (upper(name) LIKE '%"
          + term.toUpperCase() + "%') or POSITION(NAME IN '"
          + term.toUpperCase() + "')>0) ");
    }
    return cusCustomerService.findAll(request).toPage();
  }
  @RequestMapping("autocompleteUserList")
  @ResponseBody
  public PageResponse<Map<String,Object>> autocompleteUserList(JqGridRequest request,
      HttpServletRequest req) {
    String term = req.getParameter("term");
    AppUserService appUserService = ContextHolder
        .getSpringBean("appUserService");

    if (StringUtils.isNotEmpty(term)) {
      request.isPageable(false);
      request.setSelectColumns("id", "fullname","mobile","tel","department_name");
      request.setSearchString(" ((fullname is not null) and (upper(fullname) LIKE '%"
          + term.toUpperCase() + "%'))");
    }
    return appUserService.findAllDetailByRequest(request).toPage();
  }
  @RequestMapping("findDeptCountByName")
  @ResponseBody
  public List<Map<String,Object>> findDeptCountByName(JqGridRequest request,
      HttpServletRequest req) {
    String term = req.getParameter("name");
    AppDepartmentService appDepartmentService = ContextHolder
        .getSpringBean("appDepartmentService");
      request.setSelectColumns("id", "name");
      request.addFilterRule("name", JqGridFilterRuleOp.eq, term);
    return appDepartmentService.findAllDetailByRequest(request).getContent();
  }
  
  @RequestMapping("autocompleteUserDeptList")
  @ResponseBody
  public PageResponse<Map<String,Object>> autocompleteUserDeptList(JqGridRequest request,
      HttpServletRequest req) {
    String term = req.getParameter("term");
    AppDepartmentService appDepartmentService = ContextHolder
        .getSpringBean("appDepartmentService");

    if (StringUtils.isNotEmpty(term)) {
      request.isPageable(false);
      request.setSelectColumns("id", "name");
      request.setSearchString(" ((name is not null) and (upper(name) LIKE '%"
          + term.toUpperCase() + "%'))");
    }
    return appDepartmentService.findAllDetailByRequest(request).toPage();
  }
  
  @RequestMapping("autocompleteUserCustomerList")
  @ResponseBody
  public PageResponse<CusCustomer> autocompleteUserCustomerList(JqGridRequest request,
      HttpServletRequest req) {
    String term = req.getParameter("term");
    CusCustomerService cusCustomerService = ContextHolder
        .getSpringBean("cusCustomerService");

    if (StringUtils.isNotEmpty(term)) {
      request.isPageable(false);
      request.setSelectColumns("id", "name");
      request.setSearchString(" ((name is not null) and (upper(name) LIKE '%"
          + term.toUpperCase() + "%'))");
    }
    return cusCustomerService.findAll(request).toPage();
  }
  
  @RequestMapping("checkCustomerProject")
  @ResponseBody
  public List<Map<String,Object>> checkCustomerProject(JqGridRequest request,
      HttpServletRequest req) {
    String customerId = req.getParameter("customerId");
    JdbcTemplate jdbcTemplate = ContextHolder
        .getSpringBean("jdbcTemplate");
    String sql1="SELECT * FROM proj_project WHERE cus_customer_id='"+customerId+"'";
    List<Map<String,Object>> list=jdbcTemplate.queryForList(sql1);
    if(list.size()==1)
    {
      return list;
    }else if(list.size()>1)
    {
      List<Map<String,Object>> list2=new ArrayList<Map<String,Object>>();
      for(Map<String,Object> m:list)
      {
        if(m.get("cus_department_id")!=null)
        {
          Map<String,Object> tm=new HashMap<String,Object>();
          tm.put("cus_department_id", m.get("cus_department_id").toString());
          tm.put("cus_department_name", m.get("cus_department_name").toString());
          list2.add(tm);
        }
      }
      return list2;
    }else
    {
      return new ArrayList<Map<String,Object>>();
    }
    
    


  }
  
  @RequestMapping("getUserByMobile")
  @ResponseBody
  public Map<String,Object> getUserByMobile(JqGridRequest request,
      HttpServletRequest req) {
    String mobile = req.getParameter("mobile");
    AppUserService appUserService = ContextHolder
        .getSpringBean("appUserService");

    if (StringUtils.isNotEmpty(mobile)) {
      request.isPageable(false);
      request.setSelectColumns("id", "name","fullname","tel","email","address","department_name");
      request.setSearchString(" mobile='"+mobile+"'");
      request.isQueryOne(true);
    }
    return appUserService.findAllDetailByRequest(request).getContent().get(0);
  }
}
